package com.strongbj.iot.devices.newlight.request.handle;

import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.newlight.common.NetMapping;
import com.strongbj.iot.devices.newlight.entity.Reader;
import com.strongbj.iot.devices.newlight.entity.T;
import com.strongbj.iot.devices.newlight.message.NewLightMQMessage;
import com.strongbj.iot.devices.newlight.message.NewLightOSMessageFactory;
import com.strongbj.iot.devices.newlight.service.ReaderService;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

public class OpenInventoryHandle implements IMessageHandle<NewLightMQMessage, Object>{
	
	private static Logger logger = LogManager.getLogger(OpenInventoryHandle.class.getName());

	private ReaderService readerService = (ReaderService) ContextUtils.getBean("readerService");
	
	private NewLightOSMessageFactory newLightOSMessageFactory = (NewLightOSMessageFactory) ContextUtils.getBean("newLightOSMessageFactory");
	

	@Override
	public boolean isHandle(NewLightMQMessage msg) {
		if (msg.getActioncode().equals("openinventory")) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, NewLightMQMessage msg) {
		logger.info("====收到开启盘点命令====");
		String room = msg.getPostdata().toString();
		List<Reader> readers = readerService.getReadersByRoom(room);
		byte[] data = ByteUtil.hexStringToBytes("55AA");
		for (int i = 0; i < readers.size(); i++) {
			Reader reader = readers.get(i);
			byte[] req = newLightOSMessageFactory.createNewLightOSMessage(
					ByteUtil.hexStringToBytes(readers.get(i).getCode()), (byte) 0x3D, data, T.getTimeStamp());
			ByteBuf bs  = Unpooled.copiedBuffer(req);
			Channel channel = NetMapping.getInstance().getChannel(reader.getIp());
			ChannelFuture cf = channel.writeAndFlush(bs);
			cf.addListener(new ChannelFutureListener() {

				@Override
				public void operationComplete(ChannelFuture future) throws Exception {
					if (future.isSuccess()) {
						logger.info("发送打开盘点命令成功 设备编号:{} 命令={}  ", reader.getCode(),
								ByteUtil.byteArrToHexString(req, true));
					} else {
						logger.debug("发送打开盘点命令失败 设备编号:{} 命令={}  ", reader.getCode(),
								ByteUtil.byteArrToHexString(req, true));
					}
				}

			});
		}
		return null;
	}

	@Override
	public void destory() {
		// TODO Auto-generated method stub
		
	} 
}
